package com.yuyu.commons.security;



import com.yuyu.commons.annotation.AccessLimit;
import com.yuyu.commons.exception.BusinessException;
import com.yuyu.commons.redis.util.RedisUtil;
import com.yuyu.commons.toolKit.IPUtil;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Objects;

/**
 * @author
 * @version 1.0
 * @description: TODO
 * @date 2022/8/30 13:46
 */
@Component
public class AccessLimitInterceptor implements HandlerInterceptor {

    @Resource
    private RedisUtil redisUtil;

    @Override
    public boolean preHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) {
        if (handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            AccessLimit annotation = method.getAnnotation(AccessLimit.class);
            if (Objects.isNull(annotation)){
                return true;
            }
            int limit = annotation.limit();
            int second = annotation.second();
            String key = IPUtil.getIP(request) + request.getRequestURL();
            Integer nowLimit = (Integer)redisUtil.get(key);
            if (Objects.isNull(nowLimit)){
                redisUtil.set(key,1,second);
            }else if (nowLimit < limit){
                redisUtil.set(key,nowLimit+1,second);
            }else {
                throw new BusinessException("query is too frequent !");
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
